var app = getApp();
import Toast from 'tdesign-miniprogram/toast/index';
import Message from 'tdesign-miniprogram/message/index';

Component({
  options: {
    // styleIsolation: 'apply-shared',
  },
  properties: {
    // 定义传入的属性
    param1: {
      type: String,
      value: ''
    },
  },
  data: {
    gridConfig: {
      column: 1,
    },

    userInput: '',
    mode: '',
    dateVisible: false,
    type: '', // 饮食类别（breakfast等）
    mealNames: {
      breakfast: '早餐',
      lunch: '午餐',
      dinner: '晚餐',
      snack: '加餐'
    },
    date: formatDate(new Date()), // 使用自定义函数格式化当前时间
    secondVisible: false,
    second: formatTime(new Date()), // 使用自定义函数格式化当前时间

    // 对话框（提示输入title）
    confirmBtn: {
      content: '知道了',
      variant: 'base'
    },
    dialogVisibility: false,
    dialogContent: '',

    // 确认保存对话框
    confirmBtn: {
      content: '确定',
      variant: 'base'
    },
    dialogKey: '',
    showConfirm: false,
    showWarnConfirm: false,
    showTooLongBtnContent: false,
    showMultiBtn: false,

    fileList: [],
    imageNum: 3,
    imgId: '', //上传图片的id
    predHid: false,
    dietId: '', // 图片时候后返回的dietId
    segmentResults: [], // 分割后的识别结果

    // 图片识别的进度条百分比
    barPercentage: 0,

    // 轮播图
    // swiperList: [],
    swiperList: [
      // {
      //   value: "https://ericwvi.site/bgmp/api/files/download?Sid=5f0ueau6v9"
      // },
      // {
      //   value: "https://ericwvi.site/bgmp/api/files/download?Sid=5f0ueay891"
      // },
      // {
      //   value: "https://ericwvi.site/bgmp/api/files/download?Sid=5f0ueb1wzp"
      // }
    ],
    currentImage: 0,
    autoplay: false,
    duration: 500,
    interval: 0,

    current: 0,

    // 单选框
    results: [],
    // 自定义输入框
    customInputStyle: 'border: 2rpx solid var(--td-input-border-color-example);border-radius: 12rpx;',

    customFoodName: [],
    customFoodWeight: [],
    customFoodNameError: [],
    customFoodWeightError: [],
  },
  methods: {
    // 处理顶部食物描述信息
    // 未与handleCustomInput进行合并
    handleInput(e) {
      const {
        value
      } = e.detail;
      this.setData({
        userInput: value // 将用户输入的内容保存到 data 中
      });
      console.log(this.data.userInput);
    },
    // 展示toast
    showText() {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '1.自定义食物种类尚不支持营养分析\n2.请输入名称和克数',
        theme: 'success',
        direction: 'column',
      });
    },
    // 检查输入是否合理
    validateInputFormat(mode, input) {
      const trimmedInput = input.trim(); // 去除首尾空格

      // 检查输入是否为空
      if (!trimmedInput) {
        return false;
      }

      switch (mode) {
        case 'customFoodName':
          return this.validateFoodName(trimmedInput);

        case 'customFoodWeight':
          return this.validateFoodWeight(trimmedInput);

        default:
          return false;
      }
    },
    validateFoodName(value) {
      // 校验食物名称是否为中英文字符
      const foodNamePattern = /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,20}$/;
      return foodNamePattern.test(value);
    },
    validateFoodWeight(value) {
      // 校验食物重量是否为浮点数，且在0到2000之间
      const weightPattern = /^(\d+(\.\d+)?|\.\d+)$/;
      const weight = parseFloat(value);
      return weightPattern.test(value) && weight > 0 && weight <= 2000;
    },
    // 处理输入操作
    handleCustomInput(e) {
      const {
        mode
      } = e.currentTarget.dataset;
      const {
        value
      } = e.detail;
      const updatedFoodName = [...this.data[mode]]; // 复制当前数组
      const updatedFoodNameError = [...this.data[`${mode}Error`]]
      if (this.validateInputFormat(mode, value)) {
        updatedFoodName[this.data.currentImage] = value;
        updatedFoodNameError[this.data.currentImage] = false;
      } else {
        updatedFoodName[this.data.currentImage] = undefined;
        updatedFoodNameError[this.data.currentImage] = true;
      }
      this.setData({
        [mode]: updatedFoodName, // 将用户输入的内容保存到 data 中
        [`${mode}Error`]: updatedFoodNameError,
      });
      console.log('customFoodWeight', this.data.customFoodName)
      console.log('customFoodNameError', this.data.customFoodNameError)
      console.log('customFoodWeight', this.data.customFoodWeight)
      console.log('customFoodWeightError', this.data.customFoodWeightError)
    },
    showPicker(e) {
      const {
        mode
      } = e.currentTarget.dataset; // 从事件对象中获取模式值
      this.setData({
        mode,
        [`${mode}Visible`]: true,
      });
    },
    hidePicker() {
      const {
        mode
      } = this.data;
      this.setData({
        [`${mode}Visible`]: false,
      });
    },
    onConfirm(e) {
      const {
        value
      } = e?.detail;
      const {
        mode
      } = this.data;
      this.setData({
        [mode]: value,
      });

      this.hidePicker();
    },
    onColumnChange(e) {
      console.log('pick', e?.detail?.value);
    },
    handleAdd(e) {
      const {
        fileList
      } = this.data;
      const {
        files
      } = e.detail;

      // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
      this.setData({
        fileList: [...fileList, ...files], // 此时设置了 fileList 之后才会展示选择的图片
      });
      // console.log(this.data.fileList);
      this.data.fileList.forEach(file => this.uploadFile(file));
    },
    uploadFile(file) {
      console.log("upload begin", file);
      var that = this;

      const fs = wx.getFileSystemManager()
      const ab = new ArrayBuffer(file.size);
      // 打开文件
      fs.open({
        filePath: file.url,
        flag: 'r',
        success: (res) => {
          console.log("open file successfully");
          fs.read({
            fd: res.fd,
            arrayBuffer: ab,
            length: file.size,
            success: (res) => {
              console.log("read successfully", res);
              wx.request({ // 调用接口
                url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/files/upload?Name=avatar`,
                method: 'POST',
                header: {
                  "Content-Type": "image/jpeg",
                  "x-api-key": wx.getStorageSync('token')
                },
                data: ab,
                success: (res) => { // 接口调用成功，获取token并缓存
                  if (res.statusCode == 200) {
                    console.log("request");
                    console.log(res.data.message);
                    that.setData({
                      imgId: res.data.message,
                      predHid: false
                    });
                    console.log("upload successfully");
                  } else {
                    console.log("upload unsuccessfully");
                  }
                },
                fail() {
                  console.log("upload unsuccessfully");
                }
              });
            },
            fail(res) {
              console.log("read failed", res);
            }
          })
        },
        fail: (res) => {
          console.log("open file failed", res);
        }
      });
    },
    handleRemove(e) {
      const {
        index
      } = e.detail;
      const {
        fileList
      } = this.data;

      fileList.splice(index, 1);
      this.setData({
        fileList,
      });
    },
    updateImgNum(e) {
      const {
        value
      } = e.detail;
      this.setData({
        imageNum: value // 将用户输入的内容保存到 data 中
      });
      // console.log(this.data.imageNum);
    },
    showDialog(dialogContent) {
      this.setData({
        dialogVisibility: true,
        dialogContent: dialogContent
      });
    },
    closeDialog() {
      this.setData({
        dialogVisibility: false
      });
    },

    showDialog2(e) {
      const {
        key
      } = e.currentTarget.dataset;
      this.setData({
        [key]: true,
        dialogKey: key
      });
    },

    closeDialog2() {
      const {
        dialogKey
      } = this.data;
      this.setData({
        [dialogKey]: false
      });
    },
    segmentImg() {
      if (this.data.userInput === '') {
        console.log("input the comment first, please");
        this.showDialog("请先填写餐食描述信息");
        return;
      }
      if (this.data.imgId === '') {
        console.log("upload the image first, please");
        this.showDialog("请先上传图片并选择食物数量");
        return;
      }
      const {
        protocol,
        host
      } = app.globalData;
      const segmentUrl = `${protocol}://${host}/bgmp/api/diet?Action=SegRec`
      console.log(segmentUrl);

      console.log(this.data.imgId);

      var delay = 5000; // 动画延时
      var fps = 50; // 50ms 更新一次进度条
      var increment = 100 / this.data.imageNum / (delay / fps);
      var progress = 0;

      // 标志位，用于跟踪 loading 状态
      let loadingDestroyed = false;

      function updateProgress() {
        progress += increment;
        if (progress >= 99) {
          clearInterval(interval);
          progress = 99;
        }
        if (!loadingDestroyed) {
          this.setData({
            barPercentage: progress.toFixed(1)
          });
        }
      }

      var interval = setInterval(updateProgress.bind(this), fps);
      for (var i = 1; i <= this.data.imageNum; i++) {
        (function (index) {
          setTimeout(function () {
            if (!loadingDestroyed) {
              wx.hideLoading(); // 先隐藏之前的 loading
              wx.showLoading({
                title: '识别食物' + index,
              });
            }
          }.bind(this), (index - 1) * delay);
        }.bind(this))(i);
      }

      console.log("imgNum",this.data.imageNum)

      wx.request({
        url: segmentUrl,
        method: 'POST',
        header: {
          "Content-Type": "application/json",
          "x-api-key": wx.getStorageSync('token')
        },
        timeout:120000,
        data: {
          "sid": this.data.imgId,
          "num": this.data.imageNum
        },
        success: (secondApiRes) => {
          console.log("segment sucessfully:", secondApiRes);
          wx.hideLoading();
          this.setData({
            barPercentage: 0
          });

          // 销毁loading
          loadingDestroyed = true;

          if (secondApiRes.data.code === 200) {
            this.data.segmentResults = secondApiRes.data.message.results;
            this.setData({
              segmentResults: secondApiRes.data.message.results,
              dietId: secondApiRes.data.message.dietId
            });
            console.log(this.data.segmentResults);
            this.dealImg();

          } else {
            console.log(secondApiRes.data.message);
          }
        },
        fail: (secondApiError) => {
          console.log("segment failed:", secondApiError);
          this.setData({
            barPercentage: 0
          });
          wx.hideLoading();
          loadingDestroyed = true;
        }
      });
    },

    // segmentImg() {
    //   if (this.data.userInput === '') {
    //     console.log("input the comment first, please");
    //     this.showDialog("请先填写餐食描述信息");
    //     return;
    //   }
    //   if (this.data.imgId === '') {
    //     console.log("upload the image first, please");
    //     this.showDialog("请先上传图片并选择食物数量");
    //     return;
    //   }
    //   const {
    //     protocol,
    //     host
    //   } = app.globalData;
    //   const segmentUrl = `${protocol}://${host}/bgmp/api/diet?Action=SegRec`
    //   console.log(segmentUrl);

    //   // 图片上传成功后进行图片识别
    //   // this.data.imgId = JSON.parse(res.data).message;
    //   console.log(this.data.imgId);
    //   // // 显示
    //   // wx.showLoading({
    //   //   title: '识别中',
    //   // });

    //   // 计算每次 loading 的进度增量
    //   var delay = 5000; // 一个动画的延时
    //   var fps = 50; // 50ms更新一次进度条
    //   var increment = 100 / this.data.imageNum / (delay / fps);
    //   var progress = 0;

    //   // 定义更新进度条的函数
    //   function updateProgress() {
    //     progress += increment;
    //     // 如果进度达到100%，则停止更新进度条
    //     if (progress >= 99) {
    //       clearInterval(interval);
    //       progress = 99;
    //     }
    //     this.setData({
    //       barPercentage: progress.toFixed(1)
    //     });
    //   }
    //   // 循环遍历显示 loading
    //   var interval = setInterval(updateProgress.bind(this), fps);
    //   for (var i = 1; i <= this.data.imageNum; i++) {
    //     // 使用闭包来保存当前循环变量的值
    //     (function (index) {
    //       // 延迟显示 loading，并设置标题
    //       setTimeout(function () {
    //         wx.hideLoading(); // 先隐藏之前的 loading
    //         wx.showLoading({
    //           title: '识别食物' + index, // 根据当前循环变量设置标题
    //         });
    //       }.bind(this), (index - 1) * delay); // 每隔5秒显示一个标题
    //     }.bind(this))(i); // 传入当前循环变量的值
    //   }
    //   // wx.showToast({
    //   //   title: '识别中',
    //   //   icon: 'success',
    //   // });  
    //   wx.request({
    //     url: segmentUrl,
    //     method: 'POST',
    //     header: {
    //       "Content-Type": "application/json",
    //       "x-api-key": wx.getStorageSync('token')
    //     },
    //     data: {
    //       "sid": this.data.imgId,
    //       "num": this.data.imageNum
    //     },
    //     success: (secondApiRes) => {
    //       console.log("segment sucessfully:", secondApiRes);
    //       // 隐藏
    //       wx.hideLoading();
    //       this.setData({
    //         barPercentage: 0
    //       })
    //       // wx.hideToast();
    //       if (secondApiRes.data.code === 200) {
    //         this.data.segmentResults = secondApiRes.data.message.results;
    //         this.setData({
    //           segmentResults: secondApiRes.data.message.results,
    //           dietId: secondApiRes.data.message.dietId
    //         })
    //         console.log(this.data.segmentResults);
    //         this.dealImg();

    //       } else {
    //         console.log(secondApiRes.data.message);
    //       }
    //     },
    //     fail: (secondApiError) => {
    //       console.log("segment failed:", secondApiError);
    //       this.setData({
    //         barPercentage: 0
    //       })
    //       wx.hideLoading();
    //     }
    //   });
    // },
    // 处理图片地址，便于轮播图播放
    dealImg() {
      const {
        protocol,
        host
      } = app.globalData;
      const swiperList = []; // 创建一个新的数组

      // 遍历 segmentResults 数组
      this.data.segmentResults.forEach(result => {
        const imgUrl = `${protocol}://${host}/bgmp/api/files/download?Sid=${result.region}`;
        console.log(imgUrl);
        swiperList.push({
          value: imgUrl
        });
        this.data.results.push(0);
        this.data.customFoodName.push(undefined);
        this.data.customFoodNameError.push(false);
        this.data.customFoodWeight.push(undefined);
        this.data.customFoodWeightError.push(undefined);
      });

      console.log(swiperList)

      // 使用 setData 更新 swiperList
      this.setData({
        swiperList: swiperList
      });

      console.log(this.data.swiperList);
    },
    // 轮播图翻页事件
    swiperChange(e) {
      // console.log("event",e)
      const currentImage = e.detail.current;
      // console.log(currentImage)

      const currentImageValue = this.data.results[currentImage];
      if (currentImageValue !== undefined) {
        this.setData({
          currentImage: currentImage,
          current: currentImageValue
        });
      } else {
        this.setData({
          currentImage: currentImage,
          current: 0
        });
      }
      // console.log("currentImageValue",this.data.currentImageValue)
      // console.log("currentImage",this.data.currentImage)
      // console.log("current",this.data.current)
    },

    // 单选框选中事件
    radioChange(e) {
      const value = e.detail.value;
      const results = this.data.results;
      results[this.data.currentImage] = value; // 根据索引存储选中的值
      this.setData({
        results: results,
        current: value
      });
      console.log("results is ", this.data.results);
    },

    // 进行营养成分分析
    nutritionAnalysis() {
      const segmentResults = this.data.segmentResults;
      const results = this.data.results;
      const foods = []; // 选择的食物
      const customFoods = []; // 自定义食物
      for (var i = 0; i < segmentResults.length; i++) {
        if (this.data.customFoodWeight[i] == undefined || this.data.customFoodWeight[i] == undefined) {
          foods.push({
            food: segmentResults[i].food,
            region: segmentResults[i].region,
            name: segmentResults[i].top5[results[i]]
          })
        } else {
          customFoods.push({
            name: this.data.customFoodName[i],
            weight: parseFloat(this.data.customFoodWeight[i])
          })
          // foods.push({
          //   food: segmentResults[i].food,
          //   region: segmentResults[i].region,
          //   name: segmentResults[i].top5[Math.floor(Math.random() * 5)]
          // })

          function hashCode(str) {
            let hash = 0;
            for (let i = 0; i < str.length; i++) {
              const char = str.charCodeAt(i);
              hash = (hash << 5) - hash + char;
              hash |= 0; // Convert to 32bit integer
            }
            return hash;
          }
          
          const index = Math.abs(hashCode(this.data.customFoodName[i].toString())) % 5;
          
          console.log("hashCode",index)

          foods.push({
            food: segmentResults[i].food,
            region: segmentResults[i].region,
            name: segmentResults[i].top5[index]
          });

        }
      }

      console.log('foods', foods)
      console.log('customFoods', customFoods)

      const {
        protocol,
        host
      } = app.globalData;
      if (customFoods.length != 0) {
        const requests = customFoods.map(food => {
          return new Promise((resolve, reject) => {
            wx.request({
              url: `${protocol}://${host}/bgmp/api/diet?Action=AddCustomizeFood`,
              method: 'POST',
              header: {
                "Content-Type": "application/json",
                "x-api-key": wx.getStorageSync('token')
              },
              data: food,
              success: (res) => {
                console.log("customFood upload successfully", res);
                resolve(res);
              },
              fail: (res) => {
                console.log("customFood upload failed", res);
                reject(res);
              }
            });
          });
        });

        Promise.all(requests)
          .then(results => {
            console.log("All customFood upload successfully", results);
            Toast({
              context: this,
              selector: '#t-toast',
              message: '自定义食物成功',
              theme: 'success',
              direction: 'column',
            });
          })
          .catch(error => {
            console.log("Some customFood upload failed", error);
          });
      }

      // console.log(foods);
      const queryHeader = {
        dietId: this.data.dietId,
        foods: foods
      };
      // console.log(queryHeader);

      // 进行营养成分分析
      const nutritionUrl = `${protocol}://${host}/bgmp/api/diet?Action=Nutrition`
      console.log(nutritionUrl);

      // 显示
      wx.showLoading({
        title: '保存中',
      });

      wx.request({
        url: nutritionUrl,
        method: 'POST',
        header: {
          "Content-Type": "application/json",
          "x-api-key": wx.getStorageSync('token')
        },
        data: queryHeader,
        success: (res) => {
          console.log("analysis nutrition sucessfully:", res);
          // 隐藏
          wx.hideLoading();
          // wx.hideToast();

          // 上传diet的描述信息和时间
          const detailInfo = {
            "dietId": this.data.dietId,
            "comment": this.data.userInput,
            "type": this.data.type,
            "eatAt": Math.floor(new Date(this.data.date + 'T' + this.data.second).getTime() / 1000),
          }
          console.log(detailInfo);
          wx.request({
            url: `${protocol}://${host}/bgmp/api/diet?Action=SetDetail`,
            method: 'POST',
            header: {
              "Content-Type": "application/json",
              "x-api-key": wx.getStorageSync('token')
            },
            data: detailInfo,
            success: (res) => {
              console.log("detailed diet information upload successfully", res);
              Message.success({
                context: this,
                offset: [20, 32],
                duration: 1000,
                content: '饮食信息保存成功',
              });
              setTimeout(function () {
                wx.navigateBack();
              }, 2000); // 延时 2000 毫秒（2 秒）              
            },
            fail: (res) => {
              console.log("detailed diet information upload failed", res)
            }
          })
        },
        fail: (res) => {
          console.log("segment failed:", res);
        }
      });
    },
  },
  lifetimes: {
    attached: function () {
      // console.log('attached called');
      // console.log(this.properties.param1); // 输出传递的参数 'value1'
      // console.log("hhh");
      this.setData({
        type: this.properties.param1,
        date: formatDate(new Date()), // 使用自定义函数格式化当前时间
        second: formatTime(new Date()), // 使用自定义函数格式化当前时间
      })
      console.log(this.data.type);
    }
  },
});


// 自定义函数，格式化日期时间
function formatDate(date) {
  var year = date.getFullYear();
  var month = padZero(date.getMonth() + 1); //月份是从0开始的
  var day = padZero(date.getDate());
  return year + '-' + month + '-' + day;
}

// 自定义函数，格式化日期时间
function formatTime(date) {
  var hours = padZero(date.getHours());
  var minutes = padZero(date.getMinutes());
  var seconds = padZero(date.getSeconds());
  return hours + ':' + minutes + ':' + seconds;
}

// 自定义函数，补零
function padZero(num) {
  return (num < 10 ? '0' : '') + num;
}